<template>
  <CollapseItem title="Message">
    <el-form-item slot="content">
      <el-select v-model="msg" filterable clearable allow-create @visible-change="changeVisible">
        <el-option
          v-for="item in messages"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right">
            {{ item.id }}<el-button type="danger" size="mini" icon="el-icon-delete" circle @click.stop="remove(item.id)" />
          </span>
        </el-option>
      </el-select>
    </el-form-item>
  </CollapseItem>
</template>

<script>
import CollapseItem from '../../ui/CollapseItem'
import { next } from '../../../utils/tools'
import { getRoot, findRootElementsByType, getFlowElements } from '../../../utils'

const NAME = 'Message', ELEMENT_NAME = 'bpmn:' + NAME

export default {
  name: NAME,
  components: {
    CollapseItem
  },
  props: {
    element: {
      type: Object,
      required: true,
      readOnly: true
    },
    moddle: {
      type: Object,
      required: true
    },
    value: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      messages: [],
      msg: this.value
    }
  },
  watch: {
    msg(val) {
      let message
      if (val) {
        message = this.messages.find(item => item.id === val)
        if (!message) { // 新增下拉选项
          message = this.moddle.create(ELEMENT_NAME, { id: next(NAME), name: val })
          const root = getRoot(this.element)
          message.$parent = root
          root.rootElements = (root.rootElements || []).concat([message])
          this.messages.push(message)
        }
      }
      this.$emit('save-ref', message)
    }
  },
  methods: {
    remove(id) {
      let index = 0, name
      while (index < this.messages.length) {
        if (this.messages[index].id === id) {
          name = this.messages[index].name
          break
        }
        index++
      }
      if (this.msg === id || this.msg === name) {
        this.$emit('save-ref', this.msg = undefined)
        this.delete(index, id)
        return
      }
      const
        receiveTasks = getFlowElements(this.element.businessObject['$parent'], 'bpmn:ReceiveTask'),
        task = receiveTasks.find(rt => rt.messageRef?.id === id)
      if (task) { // 如果是其他ReceiveTask的messageRef
        this.$message.warning(
          this.$customTranslate('Can not remove the message which used by other ReceiveTask:{activityId}',
            { activityId: task.id }))
        return
      }
      this.delete(index, id)
    },
    delete(index, id) {
      const root = getRoot(this.element)
      root.rootElements = root.rootElements.filter(ele => ele.id !== id) // 移除对应id的Message
      this.messages.splice(index, 1)
    },
    changeVisible(show) {
      if (show) {
        this.messages = findRootElementsByType(this.element, ELEMENT_NAME)
      }
    }
  }
}
</script>
